package com.efounder.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by XinQing on 2016/9/28.
 */

public class FileUtils {

    /**
     * 读取文本
     * @param filename 文件全名（路径+文件名）
     * @return 文本
     */
    public static String readTextFile(String filename) {
        if (!new File(filename).exists()) return null;
        BufferedReader bufferedReader = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            bufferedReader = new BufferedReader(new FileReader(filename));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
                stringBuffer = stringBuffer.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭BufferedReader
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 将文本写成file文件
     * @param fileName 文件全名（路径+文件名）
     * @param text 文本
     */
    public static void writeTextFile(String fileName,String text){
        FileWriter fileWriter = null;
        try {
            File file = new File(fileName);
            if(!file.exists()) {
                File fileParent = file.getParentFile();
                if(!fileParent.exists()){
                    fileParent.mkdirs();
                }
                file.createNewFile();
            }
            fileWriter = new FileWriter(fileName);
            fileWriter.write(text);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null){
                try {
                    fileWriter.flush();
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 文件转为二进制
     *
     * @param path
     * @return
     * @throws IOException
     */
    public static byte[] FileToByte(String path) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] myByte = new byte[fileInputStream.available()];
        // 字节数
        int length = myByte.length;
        while (fileInputStream.read(myByte) != -1) {
            out.write(myByte, 0, length);
        }

        out.close();
        fileInputStream.close();
        return out.toByteArray();
    }
}
